from django.conf import settings
from django.core.management.base import BaseCommand
from django.db import transaction
from django.conf import settings
from task.models import Filter
import os

class Command(BaseCommand):
    help = 'Init Database'
    bacteriaPath = os.path.join(settings.BASE_DIR, "material", "filter", "bacteria.list")
    phagePath = os.path.join(settings.BASE_DIR, "material", "filter","phage.list")
    proPhagePath = os.path.join(settings.BASE_DIR, "material", "filter", "prophage.list")

    def parse_list_file(self, file_path):
        result = []
        with open(file_path, 'r') as f:
            lines = f.readlines()
            for line in lines:
                result.append(line.replace("\n", ""))
        return result

    @transaction.atomic()
    def handle(self, *args, **options):
        Filter.objects.all().delete()
        self.print_success("filter 数据库已经全部清空")
        phageData = self.parse_list_file(self.phagePath)
        bacteriaData = self.parse_list_file(self.bacteriaPath)
        proPhageData = self.parse_list_file(self.proPhagePath)
        Filter.objects.create(phage=phageData, pro_phage=proPhageData, bacteria=bacteriaData)
        self.print_success(f'Filter 数据库记录插入成功')
        

    def print_success(self, msg : str):
      self.stdout.write(self.style.SUCCESS(msg))

    def print_error(self, msg : str):
      self.stdout.write(self.style.ERROR(msg))